// pages/pay/index.js
import { request } from "../../request/request.js";
import {getSetting,chooseAddress,openSetting,showModal,showToast,requestPayment} from"../../utils/asyncWx.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    cart:[],
    totalPrice:0,
    totalNum:0,
    token:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo", 
    pay:{
      "timeStamp": "1564730510",
      "nonceStr": "SReWbt3nEmpJo3tr",
      "package": "prepay_id=wx02152148991420a3b39a90811023326800",
      "signType": "MD5",
      "paySign": "3A6943C3B865FA2B2C825CDCB33C5304"
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const address=wx.getStorageSync('address');
    let cart=wx.getStorageSync('cart')
    cart=cart.filter(v=>v.checked);
    this.setData({
      address:address,
      cart:cart
    })
    this.setCart(cart);
  },

  //计算总价格和数量
  setCart(cart){
    let totalPrice=0;
    let totalNum=0;
    cart.forEach(v=>{    
        totalPrice+=v.goods_price*v.num;
        totalNum+=v.num;
    })
    this.setData({     
      totalNum:totalNum,
      totalPrice:totalPrice
    });
  },

/*微信支付
1.创建订单先获取订单编号
  1.1需要头参数Authorization:token,请求体参数：order_price,consignee_addr,goods{goods_id,goods_number,goods_price}
  1.2.调用获取token的接口（所需参数：encryptedData，rawData，iv，signature，code）
  1.3.获取以上参数：调用微信api

2.获取订单编号后，发起预支付，返回一个pay
3.利用pay调用微信API正式创建订单
4.查询订单
*/
 async  handleOrderPay(){
    /*const token=wx.getStorageSync('token');*/
    try{
      const {token}=this.data;
      if(!token)
      {
          wx.navigateTo({
            url: '/pages/auth/index',
          })
      }

    else{
     const header={Authorization:token};//对象
     const order_price=this.data.totalPrice;//string
     const consignee_addr=this.data.address.all;//string
     const cart=this.data.cart;
     let goods=[];//订单数组
     cart.forEach(v=>goods.push({
       goods_id:v.goods_id,
       goods_number:v.num,
       goods_price:v.goods_price

     }))
     const orderParams={header,order_price,consignee_addr, goods}
     console.log(orderParams);
     
     //调用接口获取订单编号
     const orderNumber=await request({url:"/orders/create",data:orderParams,method:"POST"})
     console.log(orderNumber);

    //预支付  调用接口后返回pay
     const test=await request({url:"/my/orders/req_unifiedorder",data:{orderNumber},method:"POST"})
     console.log(test);
    
     //发起支付，调用微信API
     const {pay}=this.data;
     const res=await requestPayment(pay);
     console.log(res);

     //查询订单
     const status=await request({url:"/my/orders/chkOrder",data:{orderNumber},method:"POST"})
     console.log(status);
     await showToast({title:'支付成功'});
     let newCart=wx.getStorageSync('cart');
     newCart=newCart.filter(v=>!v.checked);
     wx.setStorageSync('cart', newCart);
     wx.navigateTo({
       url: "/pages/pay/index",
     })

    }
  }catch(error){
    console.log(error);
    //await showToast({title:'支付失败'});
    wx.showToast({
      title: '支付失败',
      icon:'close'
    })

  }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})